package com.yawn.spock

import spock.lang.Specification


/**
 *
 * @author yawn
 *     2019/8/28 15:40
 */
class ThrownSpec extends Specification {


    def "test exception with try-catch"() {
        when:
        int a = 1
        int b = 0
        int c = 2
        Exception ex = null
        try {
            c = (a / b)
        } catch(Exception e) {
            ex = e
        }
        then:
        ex instanceof ArithmeticException
    }

    /**
     * 测试一个方法抛出异常，可以使用try-catch在when语句块中捕获验证，但是写起来比较繁琐
     * 所以，Spock测试框架中可以使用thrown()来表示这种现象，并且可以返回异常的实例
     */
    def "test Thrown"() {
        when:
        int a = 1
        int b = 0
        int c = 2
        c = (a / b)
        then:
        def ex = thrown(Exception)
        ex instanceof ArithmeticException
    }

    /**
     * notThrown() 表示被测试的方法不会抛出某种异常
     */
    def "HashMap accepts null key"() {
        given:
        def map = new HashMap()

        when:
        map.put(null, "elem")

        then:
        notThrown(NullPointerException)
    }
}
